# -*- coding: utf-8 -*-
"""
收货地址数据访问层

负责处理收货地址相关的数据库操作
"""
from typing import Optional, List, Dict, Any
from app.repositories.base_repository import BaseRepository


class AddressRepository(BaseRepository):
    """收货地址数据访问类"""
    
    # 内存存储（用于模拟数据库）
    _memory_addresses = {}
    
    def __init__(self):
        super().__init__("user_addresses")
    
    def create_address(self, user_id: str, address_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建收货地址"""
        try:
            # 如果设置为默认地址，先将该用户的其他地址设为非默认
            if address_data.get('is_default', False):
                self._clear_default_address(user_id)
            
            # 生成地址ID
            import time
            address_id = f"ADDR{int(time.time() * 1000)}"
            
            # 插入新地址到数据库
            address_sql = """
                INSERT INTO user_addresses (
                    address_id, user_id, receiver_name, receiver_phone, 
                    province, city, district, detail_address, address_tag,
                    is_default, is_deleted, created_time, updated_time
                ) VALUES (
                    %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 0, NOW(), NOW()
                )
            """
            
            params = [
                address_id,
                user_id,
                address_data.get('name'),
                address_data.get('phone'),
                address_data.get('province'),
                address_data.get('city'),
                address_data.get('district'),
                address_data.get('detail'),
                address_data.get('type', 'home'),
                1 if address_data.get('is_default', False) else 0
            ]
            
            result = self.execute_custom_query(address_sql, params, False)
            
            if result is not None:
                # 返回创建的地址信息
                return self.find_address_by_id(address_id, user_id)
            else:
                raise Exception("数据库插入失败")
            
        except Exception as e:
            raise Exception(f"创建地址失败: {str(e)}")
    
    def update_address(self, address_id: str, user_id: str, address_data: Dict[str, Any]) -> bool:
        """更新收货地址"""
        try:
            # 检查地址是否属于该用户
            existing_address = self.execute_custom_query(
                "SELECT * FROM user_addresses WHERE address_id = %s AND user_id = %s AND is_deleted = 0",
                [address_id, user_id],
                True
            )
            
            if not existing_address:
                return False
            
            # 如果设置为默认地址，先将该用户的其他地址设为非默认
            if address_data.get('is_default', False):
                self._clear_default_address(user_id)
            
            # 构建更新SQL
            update_fields = []
            params = []
            
            field_mapping = {
                'name': 'receiver_name',
                'phone': 'receiver_phone', 
                'province': 'province',
                'city': 'city',
                'district': 'district',
                'detail': 'detail_address',
                'type': 'address_tag',
                'is_default': 'is_default'
            }
            
            for key, value in address_data.items():
                if value is not None and key in field_mapping:
                    db_field = field_mapping[key]
                    if key == 'is_default':
                        update_fields.append(f"{db_field} = %s")
                        params.append(1 if value else 0)
                    else:
                        update_fields.append(f"{db_field} = %s")
                        params.append(value)
            
            if not update_fields:
                return True  # 没有要更新的字段
                
            # 添加更新时间
            update_fields.append("updated_time = NOW()")
            params.extend([address_id, user_id])
            
            update_sql = f"""
                UPDATE user_addresses SET 
                    {', '.join(update_fields)}
                WHERE address_id = %s AND user_id = %s AND is_deleted = 0
            """
            
            result = self.execute_custom_query(update_sql, params, False)
            return result is not None
            
        except Exception as e:
            raise Exception(f"更新地址失败: {str(e)}")
    
    def delete_address(self, address_id: str, user_id: str) -> bool:
        """删除收货地址"""
        try:
            # 检查地址是否属于该用户
            existing_address = self.execute_custom_query(
                "SELECT * FROM user_addresses WHERE address_id = %s AND user_id = %s AND is_deleted = 0",
                [address_id, user_id],
                True
            )
            
            if not existing_address:
                return False
            
            # 软删除地址
            delete_sql = """
                UPDATE user_addresses SET 
                    is_deleted = 1, updated_time = NOW()
                WHERE address_id = %s AND user_id = %s
            """
            result = self.execute_custom_query(delete_sql, [address_id, user_id], False)
            
            return result is not None
            
        except Exception as e:
            raise Exception(f"删除地址失败: {str(e)}")
    
    def find_user_addresses(self, user_id: str) -> List[Dict[str, Any]]:
        """查询用户的收货地址列表"""
        try:
            addresses_sql = """
                SELECT 
                    address_id,
                    user_id,
                    receiver_name as name,
                    receiver_phone as phone,
                    province,
                    city,
                    district,
                    detail_address as detail,
                    address_tag as type,
                    is_default,
                    created_time,
                    updated_time
                FROM user_addresses 
                WHERE user_id = %s AND is_deleted = 0
                ORDER BY is_default DESC, updated_time DESC
            """
            
            addresses = self.execute_custom_query(addresses_sql, [user_id], True) or []
            
            # 转换is_default字段为布尔值
            for address in addresses:
                address['is_default'] = bool(address['is_default'])
                # 转换时间格式
                if address.get('created_time'):
                    address['created_time'] = str(address['created_time'])
                if address.get('updated_time'):
                    address['updated_time'] = str(address['updated_time'])
            
            return addresses
            
        except Exception as e:
            raise Exception(f"查询地址列表失败: {str(e)}")
    
    def find_address_by_id(self, address_id: str, user_id: str) -> Optional[Dict[str, Any]]:
        """根据ID查询单个地址"""
        try:
            address_sql = """
                SELECT 
                    address_id,
                    user_id,
                    receiver_name as name,
                    receiver_phone as phone,
                    province,
                    city,
                    district,
                    detail_address as detail,
                    address_tag as type,
                    is_default,
                    created_time,
                    updated_time
                FROM user_addresses 
                WHERE address_id = %s AND user_id = %s AND is_deleted = 0
            """
            
            result = self.execute_custom_query(address_sql, [address_id, user_id], True)
            
            if result:
                address = result[0]
                address['is_default'] = bool(address['is_default'])
                # 转换时间格式
                if address.get('created_time'):
                    address['created_time'] = str(address['created_time'])
                if address.get('updated_time'):
                    address['updated_time'] = str(address['updated_time'])
                return address
            
            return None
            
        except Exception as e:
            raise Exception(f"查询地址详情失败: {str(e)}")
    
    def set_default_address(self, address_id: str, user_id: str) -> bool:
        """设置默认地址"""
        try:
            # 检查地址是否属于该用户
            existing_address = self.execute_custom_query(
                "SELECT * FROM user_addresses WHERE address_id = %s AND user_id = %s AND is_deleted = 0",
                [address_id, user_id],
                True
            )
            
            if not existing_address:
                return False
            
            # 先将该用户的其他地址设为非默认
            self._clear_default_address(user_id)
            
            # 设置指定地址为默认
            update_sql = """
                UPDATE user_addresses SET 
                    is_default = 1, updated_time = NOW()
                WHERE address_id = %s AND user_id = %s AND is_deleted = 0
            """
            
            result = self.execute_custom_query(update_sql, [address_id, user_id], False)
            return result is not None
            
        except Exception as e:
            raise Exception(f"设置默认地址失败: {str(e)}")
    
    def _clear_default_address(self, user_id: str):
        """清除用户的默认地址设置"""
        try:
            clear_sql = "UPDATE user_addresses SET is_default = 0 WHERE user_id = %s AND is_deleted = 0"
            self.execute_custom_query(clear_sql, [user_id], False)
        except Exception as e:
            print(f"清除默认地址失败: {e}")  # 记录错误但不中断流程
    
    def _get_mock_addresses(self, user_id: str) -> List[Dict[str, Any]]:
        """获取模拟地址数据"""
        return [
            {
                "address_id": "1",
                "user_id": user_id,
                "name": "张三",
                "phone": "13812345678",
                "gender": "male",
                "type": "home",
                "province": "广东省",
                "city": "深圳市",
                "district": "南山区",
                "detail": "科技园南区深南大道10000号腾讯大厦",
                "is_default": True,
                "created_time": "2024-01-15 10:30:00",
                "updated_time": "2024-01-15 10:30:00"
            },
            {
                "address_id": "2",
                "user_id": user_id,
                "name": "李四",
                "phone": "13912345678",
                "gender": "female",
                "type": "office",
                "province": "广东省",
                "city": "广州市",
                "district": "天河区",
                "detail": "珠江新城花城大道85号高德置地广场",
                "is_default": False,
                "created_time": "2024-01-10 14:20:00",
                "updated_time": "2024-01-10 14:20:00"
            }
        ]
    
    def _get_mock_address(self, address_id: str, user_id: str) -> Optional[Dict[str, Any]]:
        """获取单个模拟地址数据"""
        mock_addresses = self._get_mock_addresses(user_id)
        for address in mock_addresses:
            if address['address_id'] == address_id:
                return address
        return None 
    def execute_custom_query(self, query: str, params: tuple = None, *args, **kwargs):
        """执行自定义查询"""
        try:
            import mysql.connector
            connection = mysql.connector.connect(**self.db_config)
            cursor = connection.cursor(dictionary=True)
            
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            result = cursor.fetchall()
            cursor.close()
            connection.close()
            
            return result if result else []
        except Exception as e:
            print(f"查询错误: {e}")
            return []
    
    def execute_query(self, query: str, params: tuple = None, *args, **kwargs):
        """执行查询"""
        return self.execute_custom_query(query, params, *args, **kwargs)
    
    def count_query(self, query: str, params: tuple = None, *args, **kwargs):
        """计数查询"""
        try:
            import mysql.connector
            connection = mysql.connector.connect(**self.db_config)
            cursor = connection.cursor()
            
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            result = cursor.fetchone()
            cursor.close()
            connection.close()
            
            return result[0] if result else 0
        except Exception as e:
            print(f"计数错误: {e}")
            return 0
